#include "map.hpp"
map::map()
{
    /*import("map1");
    mapOut();*/
}

void map::import(string path)
{
    string file = "map\\" + path + ".txt";

    fstream f (file.c_str(), fstream::in | fstream::out);
    string line;

    while(getline(f,line))
    {
        stringstream ss;
        string token;
        vector<int> tokens;
        ss << line;
        for (int i = 0; i < line.length(); i++)
        {
            tokens.push_back(atoi(line.substr(i,1).c_str()));
        }

        cmap.push_back(tokens);
        line.clear();
    }
    f.close();
}
void map::importTextures()
{
    fstream f("textures\\textures.txt", fstream::in | fstream::out);
    string line;

    while(getline(f,line))
    {
        stringstream ss;
        ss << line;
        string temp;
        vector< string > text;
        while(ss >> temp)
        {
            text.push_back(temp);
        }
        type.push_back(atoi(text[0].c_str()));
        textures.push_back(load_image("textures\\" + text[1]));
    }
}

int map::highestPoint(int x, int y)
{
    int left = highestPointRec(x,y);
    int right = highestPointRec(x+20,y);

    if(left < right)
        return left;
    else
        return right;
}
int map::highestPointRec(int x, int y)
{
    if(occupied(x,y))
        return y;
    else
        return highestPointRec(x,y+1);
}

int map::lowestPoint(int x, int y)
{
    int left = lowestPointRec(x,y);
    int right = lowestPointRec(x+20,y);

    if(left > right)
        return left;
    else
        return right;
}
int map::lowestPointRec(int x, int y)
{
    if(occupied(x,y))
        return y;
    else
        return lowestPointRec(x,y-1);
}

int map::rightMostPoint(int x, int y)
{
    int top = rightMostPointRec(x+20, y+1);
    int mid = rightMostPointRec(x+20, y+20);
    int bot = rightMostPointRec(x+20, y+38);
    int temp;
    if(top < mid)
        temp = top;
    else
        temp = mid;
    if(bot < temp)
        temp = bot;

    return temp;
}
int map::rightMostPointRec(int x, int y)
{
    if(occupied(x,y))
        return x;
    else
        return rightMostPointRec(x+1, y);
}

bool map::occupied(int x, int y)
{
    if(type[cmap[y/20][x/20]] != 1)
    {
        cmap[y/20][x/20] = 3;
        return false;
    }
    else
    {
        return true;
    }
}

void map::mapOut()
{
    for(int i = 0; i < cmap.size(); i++)
    {
        for(int k = 0; k < cmap[i].size(); k++)
        {
            cout << cmap[i][k];
        }
        cout << endl;
    }
}
void map::draw(SDL_Surface *screen)
{
    for(int i = 0; i < cmap.size(); i++)
    {
        for(int k = 0; k < cmap[i].size(); k++)
        {
            apply_surface(k*20,i*20,textures[cmap[i][k]],screen);
        }
    }
}
